package com.artron.mediaartron.ui.helper;

import android.util.DisplayMetrics;
import android.view.View;
import android.widget.TextView;

import com.artron.baselib.utils.DensityUitls;

import static com.artron.baselib.utils.UIUtils.getResources;

/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-07-25.
 */

public class ExpandTextViewHelper {

    private TextView mTvContent;
    private final int mWidthSpec;
    private final int mHeightSpec;
    private int mTvInitializeSize;

    private boolean mIsExpandable = false;
    private int mDefaultTvLines = 0;

    private boolean mIsExpanding = false;

    public ExpandTextViewHelper(TextView tvContent,int widthMarginDp) {
        mTvContent = tvContent;
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        mWidthSpec = View.MeasureSpec.makeMeasureSpec(metrics.widthPixels
                - DensityUitls.dip2px(widthMarginDp), View.MeasureSpec.AT_MOST);
        mHeightSpec = View.MeasureSpec.makeMeasureSpec(metrics.heightPixels,
                View.MeasureSpec.AT_MOST);
        measureText();
    }
    
    private void measureText(){
        mTvContent.measure(mWidthSpec, mHeightSpec);
        if (mTvInitializeSize == 0) {
            mDefaultTvLines = mTvContent.getLineCount();
            mTvInitializeSize = mTvContent.getMeasuredHeight();
            expand();
            measureText();
        } else {
            int tvHeight = mTvContent.getMeasuredHeight();
            mIsExpandable = tvHeight > mTvInitializeSize;
            shrink();
        }
    }

    public boolean isExpandable() {
        return mIsExpandable;
    }
    
    private void expand(){
        mTvContent.setMaxLines(Integer.MAX_VALUE);
        mIsExpanding = true;
    }

    private void shrink() {
        mTvContent.setMaxLines(mDefaultTvLines);
        mIsExpanding = false;
    }

    public boolean expandOrShrink() {
        if (mIsExpanding) {
            shrink();
        } else {
            expand();
        }
        return mIsExpanding;
    }
}
